package com.sw.leftrecyclerview.refresh.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.sw.leftrecyclerview.refresh.interfaces.BaseRefreshHeader;

import com.sw.leftrecyclerview.R;


public class ArrowRefreshHeader extends LinearLayout implements BaseRefreshHeader {

    private LinearLayout mContainer;
    private ImageView mArrowImageView;
    private TextView mStatusTextView;
    private int mState = STATE_NORMAL;

    private AnimationDrawable mAnimation=null;

    private static final int ROTATE_ANIM_DURATION = 180;

    public int mMeasuredWidth;
    private Context mContext;

    public ArrowRefreshHeader(Context context) {
        super(context);
        initView();
    }

    /**
     * @param context
     * @param attrs
     */
    public ArrowRefreshHeader(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    private void initView() {
        mContext = getContext();
        // 初始情况，设置下拉刷新view高度为0
        mContainer = (LinearLayout) LayoutInflater.from(getContext()).inflate(
                R.layout.listview_header, null);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
        lp.setMargins(0, 0, 0, 0);
        this.setLayoutParams(lp);
        this.setPadding(0, 0, 0, 0);

        addView(mContainer, new LayoutParams(0, LayoutParams.MATCH_PARENT));
        setGravity(Gravity.RIGHT);

        mArrowImageView = (ImageView) findViewById(R.id.listview_header_arrow);
        mStatusTextView = (TextView) findViewById(R.id.refresh_status_textview);

        measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mMeasuredWidth = getMeasuredWidth();
    }

    public void setArrowImageView(int resid) {
        mArrowImageView.setImageResource(resid);
    }

    public void setState(int state) {
        if (state == mState) return;

        if (state == STATE_REFRESHING) {    // 显示进度
            mArrowImageView.clearAnimation();
            mArrowImageView.setImageDrawable(null);
            mArrowImageView.setBackgroundResource(R.drawable.tuijianloading);
            mAnimation = (AnimationDrawable) mArrowImageView.getBackground();
            //播放动画
            mAnimation.start();
        } else if (state == STATE_DONE) {
            mArrowImageView.setBackgroundResource(0);
            mArrowImageView.setImageResource(R.drawable.yaya_loading_2);
            mArrowImageView.clearAnimation();
        } else {    // 显示箭头图片
            mArrowImageView.setVisibility(View.VISIBLE);
        }

        switch (state) {
            case STATE_NORMAL:
                if (mState == STATE_RELEASE_TO_REFRESH) {
                    mArrowImageView.setImageResource(R.drawable.yaya_loading_1);
                }
                if (mState == STATE_REFRESHING) {
                    //mArrowImageView.clearAnimation();
                }
                mStatusTextView.setText(R.string.listview_header_hint_normal);
                break;
            case STATE_RELEASE_TO_REFRESH:
                if (mState != STATE_RELEASE_TO_REFRESH) {
                    mArrowImageView.setImageResource(R.drawable.yaya_loading_2);
                    mStatusTextView.setText(R.string.listview_header_hint_release);
                }
                break;
            case STATE_REFRESHING:
                mStatusTextView.setText(R.string.refreshing);
                break;
            case STATE_DONE:
                mStatusTextView.setText(R.string.refresh_done);
                mArrowImageView.setImageResource(R.drawable.yaya_loading_1);
                break;
            default:
        }

        mState = state;
    }

    public int getState() {
        return mState;
    }

    @Override
    public void refreshComplete() {
        setState(STATE_DONE);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                reset();
            }
        }, 450);
    }

    public void setVisibleWidth(int width) {
        if (width < 0) width = 0;
        LayoutParams lp = (LayoutParams) mContainer.getLayoutParams();
        lp.width = width;
        mContainer.setLayoutParams(lp);
    }

    public int getVisibleWidth() {
        LayoutParams lp = (LayoutParams) mContainer.getLayoutParams();
        return lp.width;
    }

    @Override
    public void onMove(float delta) {
        if (getVisibleWidth() > 0 || delta > 0) {
            setVisibleWidth((int) delta + getVisibleWidth());
            if (mState <= STATE_RELEASE_TO_REFRESH) {
                setState(STATE_RELEASE_TO_REFRESH);// 未处于刷新状态，更新箭头
                if (getVisibleWidth() > mMeasuredWidth) {
                    setState(STATE_RELEASE_TO_REFRESH);
                } else {
                    setState(STATE_NORMAL);
                }
            }
        }
    }

    @Override
    public boolean releaseAction() {
        boolean isOnRefresh = false;
        int height = getVisibleWidth();
        if (height == 0) // not visible.
            isOnRefresh = false;

        if (getVisibleWidth() > mMeasuredWidth && mState < STATE_REFRESHING) {
            setState(STATE_REFRESHING);
            isOnRefresh = true;
        }
        // refreshing and header isn't shown fully. do nothing.
        if (mState == STATE_REFRESHING && height <= mMeasuredWidth) {
            //return;
        }
        int destWidth = 0; // default: scroll back to dismiss header.
        // is refreshing, just scroll back to show all the header.
        if (mState == STATE_REFRESHING) {
            destWidth = mMeasuredWidth;
        }
        smoothScrollTo(destWidth);

        return isOnRefresh;
    }

    public void reset() {
        smoothScrollTo(0);
        new Handler().postDelayed(new Runnable() {
            public void run() {
                setState(STATE_NORMAL);
            }
        }, 500);
    }

    private void smoothScrollTo(int destWidth) {
        ValueAnimator animator = ValueAnimator.ofInt(getVisibleWidth(), destWidth);
        animator.setDuration(300).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                setVisibleWidth((int) animation.getAnimatedValue());
            }
        });
        animator.start();
    }

}